package m.jclecai.com.pay;

import android.app.Activity;

import com.alibaba.fastjson.JSONObject;
import com.gyzb.sevenpay.app.PayTask;
import com.squareup.okhttp.Request;

import java.io.IOException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import m.jclecai.com.R;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.bean.PayChannelBean;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.utils.Base64;
import m.jclecai.com.utils.ChannelUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;

/**
 * Created by Dinosa on 2018/1/19.
 * 这里是七分钱的支付渠道；
 */

public class QiFenQianPayImpl extends BasePayImpl {

    private final String mUserName;
    private final String mPassword;

    String payChannel="alipay";

    public static final String RSA_PRIVATE = "MIICXQIBAAKBgQC052Cj783HWA/HYGV/Q31Qm0JWhS/Z+wC83m0Ym3CvEXux6hoq3GtDRnhJTrwThAbvVfsXdqRtUsM6zV7isF8y0mrUE1O5UgWDkxgVyZ4+RZLOFYrJWpnbQO7n2QWSfUtryhzR/eJZaXAtrWTxCo820eBo1U4gDxogwd2cOoVB9QIDAQABAoGAdcF3Ir9iT7R+8OVKrECePe4SjIc90sKUhFy03yOvggX7YqBkUCoSmEQy4GUkAAAdE4YAYBGWjqMk+g3dCeqMzEswSwjK776UEfFHfWUlIZfTcOtIpKrQjanjBOwtzUpTK5I9zOgsSwmpJhJ3vSE2tOAbcFUfWa555oqeAeHeVgECQQDom9r+B72vEV+wz0yL+Hl1JhS+81fDGA6fV/y+pO/1tIkbjm7HYwb2kcFK/FJTPuAn4ATFHniiRQn664mdVHbhAkEAxxh1iT9B+4Eu3ppoJE70bo4h+m6Kp62gl/vionA6fyMm6oJkCooOdVcRXU8bPedhsFxSlcr9TLGhG442z/sxlQJBAMGtQ+JQP7gNF0f40xuYgEjytENqCqD+3u3+LQvv+Xz0HVU8ezC5W4riQbdV8JYvvCR3eoFGpds28OBkTekZ8wECQAn+plfffxZ7I7k1EylPdWHfbME/r2I/iyJWGMiCzcz4HMoFBbSpvZQSbOK8R+fRp8vMtrCiYhjpiebyOroyKAkCQQCfjYUxjOPg6LjuDaJ1JqknM2yrvs/OoR+k3ETS9wi8EubYIFbQCre2NBvXtpI8qQLwuJpTdZt/8Oqw2EyOQ46f";


    public QiFenQianPayImpl(BaseActivity activity, String userName, String password) {
        super(activity);
        mUserName = userName;
        mPassword = password;
    }

    @Override
    public void pay(PayChannelBean channelBean, String payMoney) {
        showDialog();
        setPaying(false);
        if ("weixin".equals(channelBean.getLogo())) {
            payChannel="wx";
        }else if("sevenPay".equals(channelBean.getLogo())){
            //这里是七分钱原生的支付渠道；
            payChannel="sevenPay";
        }else{
            payChannel="alipay";
        }

        HashMap<String, String> paramsMap = new HashMap<>();

        paramsMap.put("channel","android");
        paramsMap.put("appstore", ChannelUtil.getChannel());
        paramsMap.put("money",payMoney);
        paramsMap.put("user",mUserName);
        paramsMap.put("password",mPassword);

        createChargeOrder(paramsMap);
    }

    private void createChargeOrder(HashMap<String,String> params) {

        HttpManager.postAsyn(Constant_Url.CHARGE, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {

                dissDialog();
            }

            @Override
            public void onResponse(String response) {

                dissDialog();
                JSONObject obj = FastOk.get(response, JSONObject.class);
                if(obj != null) {
                    if (obj.getString("status").equals("0")) {

                        String money = obj.getString("money");
                        String orderNumber = obj.getString("projectno");
                        setOrderNumber(orderNumber);

                        if(payChannel.equals("sevenPay")){
                            //这里我们是需要唤醒原生的操作；
                            doNativePay(money,orderNumber);
                        }else{
                            //调用h5
                            HashMap<String, String> paramsMap = new HashMap<>();
                            paramsMap.put("prodName","Account");
                            paramsMap.put("channel",payChannel);
                            paramsMap.put("prodDesc","");
                            paramsMap.put("orderAmount",money);//金额
                            paramsMap.put("mchOrderId",orderNumber);   //订单号；
                            getOrderUrl(paramsMap);
                        }

                    }else {
                        DisPlay(obj.getString("message"));
                    }
                }else {
                    DisPlay(getString(R.string.error_network));
                }


            }
        }, params);
    }

    private void doNativePay(final String money, final String orderNumber) {

        Runnable pay = new Runnable() {
            @Override
            public void run() {
                // 构造 PayTask 对象
                PayTask paytask = new PayTask((Activity)mActivity, "00");
                // 调用支付接口，获取支付结果
                String result;
                try {
                    // TODO 从服务端获取提交给七分钱的订单信息
                    String orderInfo = getOrderInfoFromServer(orderNumber,money);

                    // 调用七分钱收银台，并获取支付结果
                    result = paytask.pay(orderInfo);
                    setPaying(true);
                } catch (Exception e) {
                    result = "ERROR";
                    e.printStackTrace();
                }


            }
        };
        // 必须异步调用
        Thread payThread = new Thread(pay);
        payThread.start();
    }


    public void getOrderUrl(HashMap<String,String> params){
        showDialog();
        //这里我们将得到url;
        HttpManager.postAsyn(Constant_Url.QI_FEN_QIAN, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                //这里是对其进行另一个操作；
                //判断code，得到需要跳转的url；然后进行一个跳转
                //{"returnCode":"SUCCESS","payUrl":"https://s.qifenqian.com/s/d075c0cb3b8742eba2aa9bfb896d87e0"}
                JSONObject obj = FastOk.get(response, JSONObject.class);
                if(obj!=null){
                    String returnCode = obj.getString("returnCode");
                    //这里表示已经转入成功
                    if(returnCode != "FAILURE"){
                        setPaying(true);
                        weakUpPay(obj.getString("payUrl"));
                    }else{
                        DisPlay(returnCode);
                    }
                }else{
                    DisPlay("网络异常！！！");
                }
            }
        }, params);

    }

    public String getOrderInfoFromServer(String orderNumber,String money) throws Exception {

        String orderId = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());

        HashMap<String,String> postParams = new HashMap<String,String>();
        postParams.put("mchOrderId", orderNumber);// 商户订单号，商户网站订单系统中唯一订单号
        postParams.put("mchId", "C2018011200113"); // 商户号
        postParams.put("orderAmt",money);// 订单金额
        postParams.put("prodName","Account");// 商品名称
        postParams.put("prodDesc","");// 商品描述
        postParams.put("orderTimeOut","3600"); //订单超时时间， 单位为秒。 此处表示60分钟。60 * 60 = 3600秒
        postParams.put("orderTimestamp",timeStamp);// 订单时间戳
        postParams.put("bgUrl","http://m.fleaphp.com/payment/qifenqian/bgUrl.php");//必填， 订单完成后回调商户后台通知地址
        postParams.put("payType", "1"); // 支付方式，固定值1，不用修改
        postParams.put("pageLanguage", "1"); // 支付方式，固定值1，不用修改
        postParams.put("inputCharset","UTF-8"); // 字符集，固定值“UTF-8”,不用修改
        //postParams.put("service","mobile.plugin.pay");// 接口名称，固定值，不用修改
        postParams.put("service","h5_t.gateway.pay");// 接口名称，固定值，不用修改

        String orderInfo = genSignParam(postParams);

        String signMsg = sign(orderInfo, RSA_PRIVATE);

        System.out.println(signMsg);

        // 签名方式和签名，固定格式，请勿更改
        orderInfo += "&signType=RSA&signMsg="+signMsg;

        System.out.println("orderInfo: "+orderInfo);

        return orderInfo;
    }




    /**
     * 对待提交的参数进行排序，获取待签名字符串
     * @param paramMap
     * @return
     * @throws Exception
     */
    public static String genSignParam(Map<String, String> paramMap) throws Exception {
        if(null == paramMap || paramMap.isEmpty())
        {
            System.out.println("提交参数不能为空");
        }

        StringBuffer result = new StringBuffer();
        List<String> keyList = new ArrayList<String>();
        keyList.addAll(paramMap.keySet());

        Collections.sort(keyList);

        for(int i=0; i<keyList.size(); i++)
        {
            String key = keyList.get(i);
            String value = paramMap.get(key);
            if(null != value && !"".equals(value) )
            {
                result.append("&").append(key).append("=").append(value);
            }
        }

        return result.deleteCharAt(0).toString();
    }

    public static String sign(String content, String privateKey) {
        try {
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(
                    Base64.decode(privateKey));
            //KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
            KeyFactory keyf = KeyFactory.getInstance("RSA", "BC");
            PrivateKey priKey = keyf.generatePrivate(priPKCS8);

            java.security.Signature signature = java.security.Signature
                    .getInstance("SHA1WithRSA");

            signature.initSign(priKey);
            signature.update(content.getBytes("UTF-8"));

            byte[] signed = signature.sign();

            return parseByte2HexStr(signed);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    /**将二进制转换成16进制
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

}
